<?php
/*
Plugin Name: Category Archives
Plugin URI: 
Description: Adds Category Filtering to Post Archives
Author: Martin Alterisio
Version: 0.2.1
Author URI: http://www.google.com/profiles/malterisio777
*/

function category_archives_activate() {
	global $wp_rewrite;
	$wp_rewrite->flush_rules();
}
register_activation_hook(__FILE__, 'category_archives_activate');

function category_archives_deactivate() {
	global $wp_rewrite;
	$wp_rewrite->flush_rules();
}
register_deactivation_hook(__FILE__, 'category_archives_deactivate');

function category_archives_widget_init() {
	require_once dirname(__FILE__).'/widget.php';
}
add_action('widgets_init', 'category_archives_widget_init');

function category_archives_rewrite_rules($rules) {
	global $wp_rewrite;
	preg_match('~^(/index\\.php)?(/.*)$~', $wp_rewrite->get_category_permastruct(), $category_permastruct);
	preg_match('~^(/index\\.php)?(/.*)$~', $wp_rewrite->get_date_permastruct(), $date_permastruct);
	$permastruct = $category_permastruct[1] . $category_permastruct[2] . $date_permastruct[2];
	return array_merge($wp_rewrite->generate_rewrite_rules($permastruct, EP_NONE), $rules);
}
add_filter('category_rewrite_rules', 'category_archives_rewrite_rules');
	
function category_archives_where_filter($where, $args) {
	global $wpdb;
	if ($category = (int)$args['category']) {
		$where .= " AND $wpdb->term_taxonomy.taxonomy = 'category' AND $wpdb->term_taxonomy.term_id = $category ";
	}
	return $where;
}
add_filter('getarchives_where', 'category_archives_where_filter', 10, 2);

function category_archives_join_filter($join, $args) {
	global $wpdb;
	if ((int)$args['category']) {
		$join .= " INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) ";
	}
	return $join;
}
add_filter('getarchives_join', 'category_archives_join_filter', 10, 2);

function category_archives_link_filter($url) {
	static $url_root_regex = null;
	if (!$url_root_regex) $url_root_regex = '~^'.preg_quote(trailingslashit(get_option('home')), '~').'(index\\.php/)?~';
	foreach (debug_backtrace() as $call) if ($call['function'] == 'wp_get_archives') {
		$args = wp_parse_args($call['args'][0]);
		if ($category = $args['category']) {
			$url = preg_replace($url_root_regex, '', $url);
			if ($url[0] == '?') $url[0] = '&';
			$url = get_category_link($category) . $url;
		}
		break;
	}
	return $url;
}
add_filter('year_link', 'category_archives_link_filter');
add_filter('month_link', 'category_archives_link_filter');
add_filter('day_link', 'category_archives_link_filter');
